package com.iris.live.services.common;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;

import java.util.List;

/**
 * 极光推送工具类
 */
public class JPush {
    // iTask相关属性
    private static final String iTaskAppKey = "665be901b028ac2e44735526";
    private static final String iTaskMasterSecret = "05e0687405df6e2e30cdc8bc";
    // iManagement相关属性
    private static final String iMgtAppKey = "d021ac0664324ec1393eec85";
    private static final String iMgtMasterSecret = "72784408378b1ec36a95d700";
    // 测试用变量
    private static final String TITLE = "Test from API example";
    private static final String ALERT = "Test from API Example - alert";
    private static final String MSG_CONTENT = "Test from API Example - msgContent";
    private static final String REGISTRATION_ID = "0900e8d85ef";
    private static final String TAG = "tag_api";
    // 日志
    private static final Logger logger = LoggerFactory.getLogger(JPush.class);

    // 对iTask推送消息方法，默认iTask
    @Async
    public static void SendPushITaskForAndroidAndIos(String alert, String msg_content, JsonObject json, List reclist) {
        sendPushForAndroidAndIos(alert, msg_content, json, reclist, Platforms.iTask);
    }

    /**
     * Mgt iManagement 系统
     * A Android平台
     * i iOS平台
     */
    @Async
    public static void sendMsgToMgtAi(String alert, String msgContent, JsonObject json, List<String> recList) {
        sendPushForAndroidAndIos(alert, msgContent, json, recList, Platforms.iMgt);
    }

    //重写，对选择的平台发送推送，暂时是iTask和iMgt
    public static void sendPushForAndroidAndIos(String alert, String msg_content, JsonObject json, List reclist, Platforms platform) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        // 定义推送到哪个APP
        JPushClient jpushClient = new JPushClient(platform.getValue(), platform.getKey(), null, clientConfig);
        // 推送对象
        PushPayload payload = buildPushMsg(alert, msg_content, json, reclist);
        try {
            // 推送动作
            PushResult result = jpushClient.sendPush(payload);
            logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
            logger.error(e.getMessage());
        } catch (APIRequestException e) {
            logger.error("HTTP Status:{}, Error Code:{}, Error Message:{}, Msg ID:", e.getStatus(), e.getErrorCode(), e.getErrorMessage(), e.getMsgId());
        }
    }

    /**
     * @param alert       消息推送的消息头？
     * @param msg_content 消息内容
     * @param json        对方解析extra时候约定的参数和值
     * @param reclist     推送对象
     * @return
     */
    public static PushPayload buildPushMsg(String alert, String msg_content, JsonObject json, List reclist) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(reclist))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .autoBadge()
                                .setSound("happy")
                                .addExtra("data", json)
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                //添加原因:安卓端接收不到附加消息内容
                                .addExtra("data", json)
                                .build())
                        .build())
                .setMessage(Message.content(msg_content))
                .setOptions(Options.newBuilder()
                        // 项目后期可能会更改为true
                        .setApnsProduction(true)
//                        .setApnsProduction(false)
                        .build())
                .build();
    }

    public enum Platforms {
        iTask(iTaskAppKey, iTaskMasterSecret), iMgt(iMgtAppKey, iMgtMasterSecret);
        private String key;
        private String value;

        private Platforms(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
